<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量导入敏感词"
    width="800px"
    :before-close="handleClose"
  >
    <div class="import-container">
      <!-- 导入步骤 -->
      <el-steps :active="currentStep" align-center class="import-steps">
        <el-step title="选择文件" description="上传Excel或CSV文件" />
        <el-step title="配置参数" description="设置导入选项" />
        <el-step title="预览数据" description="确认导入内容" />
        <el-step title="导入完成" description="查看导入结果" />
      </el-steps>

      <!-- 步骤1: 文件上传 -->
      <div v-if="currentStep === 0" class="step-content">
        <div class="upload-section">
          <el-upload
            ref="uploadRef"
            class="upload-dragger"
            drag
            :auto-upload="false"
            :limit="1"
            :accept="'.xlsx,.xls,.csv'"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .xlsx、.xls、.csv 格式，文件大小不超过 10MB
              </div>
            </template>
          </el-upload>

          <!-- 文件信息 -->
          <div v-if="selectedFile" class="file-info">
            <el-card>
              <div class="file-details">
                <el-icon><Document /></el-icon>
                <div class="file-meta">
                  <div class="file-name">{{ selectedFile.name }}</div>
                  <div class="file-size">
                    {{ formatFileSize(selectedFile.size) }}
                  </div>
                </div>
                <el-button type="danger" size="small" @click="removeFile">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </el-card>
          </div>

          <!-- 模板下载 -->
          <div class="template-section">
            <el-alert
              title="导入格式说明"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>请按照以下格式准备数据：</p>
                <ul>
                  <li>第一列：敏感词内容（必填）</li>
                  <li>第二列：类型（可选，如：profanity、politics等）</li>
                  <li>第三列：严重程度（可选，1-5的数字）</li>
                  <li>第四列：过滤模式（可选，REPLACE或BLOCK）</li>
                  <li>第五列：替换文本（可选）</li>
                  <li>第六列：描述信息（可选）</li>
                </ul>
              </template>
            </el-alert>
            <div class="template-actions">
              <el-button type="primary" @click="downloadTemplate">
                <el-icon><Download /></el-icon>
                下载模板文件
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 步骤2: 配置参数 -->
      <div v-if="currentStep === 1" class="step-content">
        <el-form :model="importConfig" label-width="120px">
          <el-form-item label="默认类型">
            <el-select
              v-model="importConfig.defaultType"
              placeholder="选择默认敏感词类型"
              style="width: 100%"
            >
              <el-option
                v-for="type in sensitiveWordTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
            <div class="form-tip">当文件中未指定类型时使用此默认值</div>
          </el-form-item>

          <el-form-item label="默认严重程度">
            <el-select
              v-model="importConfig.defaultSeverity"
              placeholder="选择默认严重程度"
              style="width: 100%"
            >
              <el-option
                v-for="severity in severityLevels"
                :key="severity.value"
                :label="severity.label"
                :value="severity.value"
              />
            </el-select>
            <div class="form-tip">当文件中未指定严重程度时使用此默认值</div>
          </el-form-item>

          <el-form-item label="覆盖策略">
            <el-radio-group v-model="importConfig.overwrite">
              <el-radio :value="false">跳过已存在的敏感词</el-radio>
              <el-radio :value="true">覆盖已存在的敏感词</el-radio>
            </el-radio-group>
            <div class="form-tip">选择如何处理已存在的敏感词</div>
          </el-form-item>

          <el-form-item label="数据验证">
            <el-checkbox-group v-model="importConfig.validationOptions">
              <el-checkbox value="checkDuplicate">检查重复数据</el-checkbox>
              <el-checkbox value="validateFormat">验证数据格式</el-checkbox>
              <el-checkbox value="filterEmpty">过滤空行</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤3: 数据预览 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="preview-section">
          <div class="preview-header">
            <h4>数据预览（前10条）</h4>
            <el-text type="info">
              共解析到 {{ previewData.length }} 条数据
            </el-text>
          </div>

          <el-table
            :data="previewData.slice(0, 10)"
            border
            stripe
            max-height="300"
          >
            <el-table-column prop="word" label="敏感词" width="150" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag size="small">{{ getTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="severity" label="严重程度" width="100">
              <template #default="{ row }">
                <el-tag size="small">{{
                  getSeverityLabel(row.severity)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="filterMode" label="过滤模式" width="100" />
            <el-table-column prop="replacement" label="替换文本" width="100" />
            <el-table-column prop="description" label="描述" min-width="150" />
          </el-table>

          <!-- 验证结果 -->
          <div v-if="validationErrors.length > 0" class="validation-errors">
            <el-alert
              title="数据验证警告"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <div class="error-list">
                  <div
                    v-for="error in validationErrors.slice(0, 5)"
                    :key="error.line"
                    class="error-item"
                  >
                    第{{ error.line }}行: {{ error.error }}
                  </div>
                  <div v-if="validationErrors.length > 5" class="error-more">
                    还有 {{ validationErrors.length - 5 }} 个错误...
                  </div>
                </div>
              </template>
            </el-alert>
          </div>
        </div>
      </div>

      <!-- 步骤4: 导入结果 -->
      <div v-if="currentStep === 3" class="step-content">
        <div class="result-section">
          <div class="result-summary">
            <el-result
              :icon="importResult.successCount > 0 ? 'success' : 'warning'"
              :title="importResult.successCount > 0 ? '导入完成' : '导入失败'"
            >
              <template #sub-title>
                <div class="result-stats">
                  <div class="stat-item success">
                    <span class="stat-label">成功:</span>
                    <span class="stat-value">{{
                      importResult.successCount
                    }}</span>
                  </div>
                  <div class="stat-item skip">
                    <span class="stat-label">跳过:</span>
                    <span class="stat-value">{{ importResult.skipCount }}</span>
                  </div>
                  <div class="stat-item error">
                    <span class="stat-label">失败:</span>
                    <span class="stat-value">{{
                      importResult.failureCount
                    }}</span>
                  </div>
                </div>
              </template>
            </el-result>
          </div>

          <!-- 错误详情 -->
          <div v-if="importResult.errors.length > 0" class="error-details">
            <h4>错误详情</h4>
            <el-table
              :data="importResult.errors"
              border
              stripe
              max-height="200"
            >
              <el-table-column prop="line" label="行号" width="80" />
              <el-table-column prop="word" label="敏感词" width="150" />
              <el-table-column prop="error" label="错误信息" min-width="200" />
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button @click="handleClose">
          {{ currentStep === 3 ? "完成" : "取消" }}
        </el-button>
        <el-button
          v-if="currentStep < 3"
          type="primary"
          :disabled="!canNextStep"
          :loading="processing"
          @click="nextStep"
        >
          {{ currentStep === 2 ? "开始导入" : "下一步" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  UploadFilled,
  Document,
  Delete,
  Download
} from "@element-plus/icons-vue";
import {
  importSensitiveWordsApi,
  SensitiveWordType,
  SeverityLevel,
  type ImportSensitiveWordsParams,
  type ImportResult
} from "@/api/sensitive-word-management";

interface Props {
  /** 对话框可见性 */
  visible: boolean;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  "update:visible": [visible: boolean];
  success: [];
}>();

// 响应式数据
const currentStep = ref(0);
const processing = ref(false);
const uploadRef = ref();
const selectedFile = ref<File | null>(null);
const previewData = ref<any[]>([]);
const validationErrors = ref<any[]>([]);

// 导入配置
const importConfig = reactive({
  defaultType: SensitiveWordType.PROFANITY,
  defaultSeverity: SeverityLevel.MEDIUM,
  overwrite: false,
  validationOptions: ["checkDuplicate", "validateFormat", "filterEmpty"]
});

// 导入结果
const importResult = reactive<ImportResult>({
  successCount: 0,
  failureCount: 0,
  skipCount: 0,
  errors: []
});

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const canNextStep = computed(() => {
  switch (currentStep.value) {
    case 0:
      return selectedFile.value !== null;
    case 1:
      return true;
    case 2:
      return previewData.value.length > 0;
    default:
      return false;
  }
});

// 选项数据
const sensitiveWordTypes = [
  { label: "脏话", value: SensitiveWordType.PROFANITY },
  { label: "政治敏感", value: SensitiveWordType.POLITICS },
  { label: "广告", value: SensitiveWordType.ADVERTISEMENT },
  { label: "暴力内容", value: SensitiveWordType.VIOLENCE },
  { label: "违法内容", value: SensitiveWordType.ILLEGAL },
  { label: "垃圾信息", value: SensitiveWordType.SPAM }
];

const severityLevels = [
  { label: "轻微", value: SeverityLevel.LIGHT },
  { label: "一般", value: SeverityLevel.NORMAL },
  { label: "中等", value: SeverityLevel.MEDIUM },
  { label: "严重", value: SeverityLevel.SERIOUS },
  { label: "极严重", value: SeverityLevel.CRITICAL }
];

// 工具函数
const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
};

const getTypeLabel = (type: string) => {
  return sensitiveWordTypes.find(t => t.value === type)?.label || type;
};

const getSeverityLabel = (severity: number) => {
  return (
    severityLevels.find(s => s.value === severity)?.label || severity.toString()
  );
};

// 文件处理
const handleFileChange = (file: any) => {
  selectedFile.value = file.raw;
};

const handleExceed = () => {
  ElMessage.warning("只能上传一个文件");
};

const removeFile = () => {
  selectedFile.value = null;
  uploadRef.value?.clearFiles();
};

// 下载模板
const downloadTemplate = () => {
  // 创建模板数据
  const templateData = [
    ["敏感词", "类型", "严重程度", "过滤模式", "替换文本", "描述"],
    ["示例敏感词1", "profanity", "3", "REPLACE", "***", "示例描述"],
    ["示例敏感词2", "politics", "4", "BLOCK", "", "政治敏感内容"]
  ];

  // 创建CSV内容
  const csvContent = templateData.map(row => row.join(",")).join("\n");
  const blob = new Blob(["\uFEFF" + csvContent], {
    type: "text/csv;charset=utf-8;"
  });

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "敏感词导入模板.csv";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);

  ElMessage.success("模板文件下载成功");
};

// 步骤控制
const nextStep = async () => {
  if (currentStep.value === 1) {
    await parseFile();
  } else if (currentStep.value === 2) {
    await performImport();
  } else {
    currentStep.value++;
  }
};

const prevStep = () => {
  currentStep.value--;
};

// 解析文件
const parseFile = async () => {
  if (!selectedFile.value) return;

  try {
    processing.value = true;

    // 这里应该调用文件解析API或使用前端解析库
    // 模拟解析结果
    previewData.value = [
      {
        word: "测试敏感词1",
        type: SensitiveWordType.PROFANITY,
        severity: SeverityLevel.MEDIUM,
        filterMode: "REPLACE",
        replacement: "***",
        description: "测试用敏感词"
      },
      {
        word: "测试敏感词2",
        type: SensitiveWordType.POLITICS,
        severity: SeverityLevel.SERIOUS,
        filterMode: "BLOCK",
        replacement: "",
        description: "政治敏感内容"
      }
    ];

    validationErrors.value = [];
    currentStep.value++;
  } catch (error) {
    console.error("文件解析失败:", error);
    ElMessage.error("文件解析失败");
  } finally {
    processing.value = false;
  }
};

// 执行导入
const performImport = async () => {
  try {
    processing.value = true;

    // 准备导入参数
    const params: ImportSensitiveWordsParams = {
      fileContent: "", // 这里应该是文件的Base64内容
      fileName: selectedFile.value?.name || "",
      overwrite: importConfig.overwrite,
      defaultType: importConfig.defaultType,
      defaultSeverity: importConfig.defaultSeverity
    };

    const response = await importSensitiveWordsApi(params);

    if (response.code === 200 && response.data) {
      Object.assign(importResult, response.data);
      currentStep.value++;

      if (importResult.successCount > 0) {
        ElMessage.success(`成功导入 ${importResult.successCount} 条敏感词`);
      }
    } else {
      ElMessage.error(response.message || "导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  } finally {
    processing.value = false;
  }
};

// 重置状态
const resetState = () => {
  currentStep.value = 0;
  selectedFile.value = null;
  previewData.value = [];
  validationErrors.value = [];
  Object.assign(importResult, {
    successCount: 0,
    failureCount: 0,
    skipCount: 0,
    errors: []
  });
  uploadRef.value?.clearFiles();
};

// 关闭对话框
const handleClose = () => {
  if (currentStep.value === 3 && importResult.successCount > 0) {
    emit("success");
  }
  dialogVisible.value = false;
  resetState();
};
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .result-stats {
    flex-direction: column;
    gap: 16px;
  }

  .preview-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

.import-container {
  padding: 20px 0;
}

.import-steps {
  margin-bottom: 32px;
}

.step-content {
  min-height: 300px;
}

.upload-section {
  text-align: center;
}

.upload-dragger {
  width: 100%;
}

.file-info {
  margin: 20px 0;
}

.file-details {
  display: flex;
  gap: 12px;
  align-items: center;
}

.file-meta {
  flex: 1;
  text-align: left;
}

.file-name {
  font-weight: 600;
  color: #333;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.template-section {
  margin-top: 24px;
  text-align: left;
}

.template-actions {
  margin-top: 16px;
  text-align: center;
}

.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #666;
}

.preview-section {
  padding: 16px 0;
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.preview-header h4 {
  margin: 0;
}

.validation-errors {
  margin-top: 16px;
}

.error-list {
  font-size: 14px;
}

.error-item {
  margin-bottom: 4px;
}

.error-more {
  font-style: italic;
  color: #666;
}

.result-section {
  text-align: center;
}

.result-stats {
  display: flex;
  gap: 24px;
  justify-content: center;
  margin-top: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-value {
  margin-top: 4px;
  font-size: 24px;
  font-weight: bold;
}

.stat-item.success .stat-value {
  color: #67c23a;
}

.stat-item.skip .stat-value {
  color: #e6a23c;
}

.stat-item.error .stat-value {
  color: #f56c6c;
}

.error-details {
  margin-top: 24px;
  text-align: left;
}

.error-details h4 {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: center;
}
</style>
